import re
from user.models import User

# 自定义jwt认证返回数据(重写方法)
from django.contrib.auth.backends import ModelBackend


def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }

# 由于django中自带的登录验证只提供用户名登录验证，我们需要重写此方法用于添加手机号与密码登录
class MobileUserBackend(ModelBackend):

    # 重写authenticate方法
    def authenticate(self, request, username=None, password=None, **kwargs):

        try:
            # 判断输入的是用户名还是电话号码
            if re.match(r'^1[3-9]\d{9}$', username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except:
            user = None
        if user and user.check_password(password):
            return user

